<script>
export default {
  name: "InputMsg",
  data() {
    return {
      hobbyArray: ["吃饭", "睡觉", "玩游戏", "敲代码"],
      formValidate: {
        username: "",
        userId: "",
        hobby: [],
        age: 18,
      },
      ruleValidate: {
        username: [{ required: true, message: "还没有输入用户名", trigger: "blur" }],
        userId: [{ required: true, message: "还没有输入用户名", trigger: "blur" }],
        hobby: [
          {
            required: true,
            type: "array",
            min: 1,
            message: "请至少选择一个爱好",
            trigger: "change",
          },
        ],
      },
    };
  },
  props: { updataFlag: Boolean, userMsg: Object },
  methods: {
    handleSubmit(name, msg) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$emit("getMsg", msg);
        } else {
          this.$Message.error("请输入完整信息");
        }
      });
    },
    handleReset(name) {
      console.log(this.$refs[name]);
      this.$refs[name].resetFields();
    },
    //v-model
    onInput(key,e){
      this.formValidate[key]=e
    }
  },
  render() {
    
    return (
      <Form ref="formValidate" props={{model:this.formValidate}}   rules={this.ruleValidate} label-width={80}>
        <FormItem label="用户名" prop="username">
          <Input onInput={this.onInput.bind(this,'username')} value={this.formValidate.username}  placeholder="请输入用户名"></Input>
        </FormItem>
        <FormItem label="爱好" prop="hobby">
          <CheckboxGroup onInput={this.onInput.bind(this,'hobby')}  value={this.formValidate.hobby}>
          {this.hobbyArray.map((item)=>{
            return <Checkbox
              label={item}
            ></Checkbox>
          })}

          </CheckboxGroup>
        </FormItem>
        <FormItem label="年龄" prop="age">
          <InputNumber onInput={this.onInput.bind(this,'age')} controls-outside min={1}  value={this.formValidate.age}></InputNumber>
        </FormItem>

        <FormItem>
          <Button type="primary" onClick={this.handleSubmit.bind(this,'formValidate', this.formValidate)}>
            {this.updataFlag ? "修改信息" : "创建用户"}
          </Button>
          <Button onClick={this.handleReset.bind(this,'formValidate')} style="margin-left: 8px">
            清除信息
          </Button>
        </FormItem>
      </Form>
    );
  },
  created() {
    if (this.userMsg) {
      let { username, age, hobby } = this.userMsg;
      Object.assign(this.formValidate, { username, age, hobby });
    }
  },
};
</script>
